package com.dong.zhaofengcontact2018.activity;

import android.arch.core.executor.TaskExecutor;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.dong.zhaofengcontact2018.BuildConfig;
import com.dong.zhaofengcontact2018.R;
import com.dong.zhaofengcontact2018.model.Folk;

import java.util.ArrayList;

public class FindSystemContactThenSaveToThisAppActivity extends AppCompatActivity {

    private ListView mContactFromMobileListView;
    private MyAsyncQureyHandler mAsyncQureyHandler;
    private ArrayList<Folk> mFolkArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_system_contact_then_save_to_this_app);

        mContactFromMobileListView = findViewById(R.id.listview_contact_from_mobile__find_system_contact_then_save_to_this_app);
        initData();

    }

    private void initData() {

        new AsyncTask<Object, Object, ArrayList<Folk>>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mFolkArrayList = new ArrayList<>();
            }

            @Override
            protected ArrayList<Folk> doInBackground(Object... objects) {

                String id;

                ContentResolver contentResolver = getContentResolver();
                //只需要从Contacts中获取ID，其他的都可以不要，通过查看上面编译后的SQL语句，可以看出将第二个参数
                //设置成null，默认返回的列非常多，是一种资源浪费。
                Cursor cursorAllPersonId = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
                        new String[]{ContactsContract.Contacts._ID}, null, null, null);
                Cursor cursorEachPerson = null;

                Folk folk;

                while (cursorAllPersonId.moveToNext()) {
                    folk = new Folk();
                    id = cursorAllPersonId.getString(cursorAllPersonId.getColumnIndex(ContactsContract.Contacts._ID));
                    cursorEachPerson = contentResolver.query(
                            ContactsContract.Data.CONTENT_URI,
//                            new String[]{
//                                    ContactsContract.Data.MIMETYPE,
//                                    ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,// 姓名
//                                    ContactsContract.CommonDataKinds.SipAddress.DISPLAY_NAME,
//                                    ContactsContract.CommonDataKinds.Organization.COMPANY,
//                                    ContactsContract.CommonDataKinds.Organization.TITLE,
//                                    ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
//                                    ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME,
//                                    ContactsContract.CommonDataKinds.Im.DISPLAY_NAME,
//                                    ContactsContract.CommonDataKinds.Email.DATA,// EMail
//                                    ContactsContract.CommonDataKinds.Phone.NUMBER,// 电话
//                                    ContactsContract.CommonDataKinds.StructuredPostal.DATA,// 地址
//                            },
                            null,
                            ContactsContract.Data.CONTACT_ID + "=" + id, null, null);

                    String mimetype;
                    String str;
                    while (cursorEachPerson.moveToNext()) {
                        mimetype = cursorEachPerson.getString(cursorEachPerson.getColumnIndex(ContactsContract.Data.MIMETYPE));
                        if ("vnd.android.cursor.item/name".equals(mimetype)) {
                            str = cursorEachPerson.getString(cursorEachPerson.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
                            folk.setName(str);
                        } else if ("vnd.android.cursor.item/sip_address".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/nickname".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
                            str = cursorEachPerson.getString(cursorEachPerson.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            str = str.replaceAll("[- ]","");
                            folk.setPhones(     TextUtils.isEmpty(     folk.getPhones()     ) ? str:     folk.getPhones() + ","+str                        );

                        } else if ("vnd.android.cursor.item/group_membership".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/organization".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/im".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/postal-address_v2".equals(mimetype)) {
                            str = cursorEachPerson.getString(cursorEachPerson.getColumnIndex( ContactsContract.CommonDataKinds.StructuredPostal.DATA));
                            folk.setAddress(str);
                        } else if ("vnd.android.cursor.item/identity".equals(mimetype)) {
                        } else if ("vnd.android.cursor.item/photo".equals(mimetype)) {
                        } else if ("data1".equals(mimetype)) {


                        }

                    }
                    mFolkArrayList.add(folk);
                }
                System.out.println(mFolkArrayList.toString());
                return mFolkArrayList;
            }

            @Override
            protected void onProgressUpdate(Object... values) {
                super.onProgressUpdate(values);
            }

            @Override
            protected void onPostExecute(ArrayList<Folk> folks) {
                super.onPostExecute(folks);

            }
        }.execute();


//        new AsyncTask<Object, Object, String>() {
//
//            private ArrayList<Folk> mFolks = new ArrayList<>();
//
//            @Override
//            protected String doInBackground(Object... objects) {
//
//
//                String id;
//                String mimetype;
//                ContentResolver contentResolver = getContentResolver();
//                //只需要从Contacts中获取ID，其他的都可以不要，通过查看上面编译后的SQL语句，可以看出将第二个参数
//                //设置成null，默认返回的列非常多，是一种资源浪费。
//                Cursor cursor = contentResolver.query(android.provider.ContactsContract.Contacts.CONTENT_URI,
//                        new String[]{android.provider.ContactsContract.Contacts._ID}, null, null, null);
//                Contacts contactitem;
//                while (cursor.moveToNext()) {
//                    contactitem = new Contacts();//查询的要创建新的contacts对象
//                    id = cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts._ID));
//                    //从一个Cursor获取所有的信息
//                    Cursor contactInfoCursor = contentResolver.query(
//                            android.provider.ContactsContract.Data.CONTENT_URI,
//                            new String[]{android.provider.ContactsContract.Data.CONTACT_ID,
//                                    android.provider.ContactsContract.Data.MIMETYPE,
//                                    android.provider.ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, //用户名
//                                    android.provider.ContactsContract.CommonDataKinds.Organization.COMPANY,//公司
//                                    android.provider.ContactsContract.CommonDataKinds.Organization.TITLE,//职称
//                                    android.provider.ContactsContract.CommonDataKinds.Phone.TYPE,//电话属性
//                                    android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER,// 电话号码
//                                    android.provider.ContactsContract.CommonDataKinds.Email.TYPE,//邮件属性
//                                    android.provider.ContactsContract.CommonDataKinds.Email.DATA,//邮件信息
//                                    android.provider.ContactsContract.CommonDataKinds.Note.NOTE,//备注
//                                    android.provider.ContactsContract.Data.DATA1,//查询的细节
//                                    android.provider.ContactsContract.Data.DATA5
//                            },
//                            android.provider.ContactsContract.Data.CONTACT_ID + "=" + id, null, null);
//                    while (contactInfoCursor.moveToNext()) {
//                        mimetype = contactInfoCursor.getString(contactInfoCursor.getColumnIndex(android.provider.ContactsContract.Data.MIMETYPE));
//
//                        if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)) {
//                            String name = contactInfoCursor.getString(contactInfoCursor.getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
//                            //LogUtils.E("====name==="+name);
//                            contactitem.setName(name);
//                        } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)) {
//                            String org = contactInfoCursor.getString(contactInfoCursor.getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Organization.COMPANY));
//                            String title = contactInfoCursor.getString(contactInfoCursor.getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Organization.TITLE));
//                            String department = contactInfoCursor.getString(contactInfoCursor.getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
//                            //LogUtils.E("====org==="+org+","+title);
//                            contactitem.setOrganization(org);
//                            contactitem.setJobtitle(title);
//                            contactitem.setDepartment(department);
//                        } else if (mimetype.equals(Phone.CONTENT_ITEM_TYPE)) {
//                            String type = contactInfoCursor.getString(contactInfoCursor.getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Phone.TYPE));
//                            String number;
//                            String phonename = null;
//                            int a = Integer.parseInt(type);
//                            switch (a) {
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
//                                    phonename = "mobile";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_MAIN:
//                                    phonename = "main";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
//                                    phonename = "home";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
//                                    phonename = "work";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK:
//                                    phonename = "fax_work";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:
//                                    phonename = "fax_home";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
//                                    phonename = "other";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM:
//                                    phonename = "custom";
//                                    break;
//                            }
//                            number = contactInfoCursor.getString(contactInfoCursor
//                                    .getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER));
//                            //LogUtils.E("====phone==="+phonename+","+number);
//                            ContactFields cf = new ContactFields("Contact::Phone", phonename, number);
//                            contactitem.contact_fields.add(cf);
//
//                        } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
//                            String type = contactInfoCursor.getString(contactInfoCursor
//                                    .getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Email.TYPE));
//                            String emailname = null;
//                            switch (Integer.parseInt(type)) {
//                                case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
//                                    emailname = "work";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM:
//                                    emailname = "custom";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE:
//                                    emailname = "mobile";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
//                                    emailname = "home";
//                                    break;
//                                case ContactsContract.CommonDataKinds.Email.TYPE_OTHER:
//                                    emailname = "other";
//                                    break;
//                            }
//                            String date = contactInfoCursor.getString(contactInfoCursor
//                                    .getColumnIndexOrThrow(android.provider.ContactsContract.CommonDataKinds.Email.DATA));
//                            //LogUtils.E("====email==="+emailname+","+date);
//                            ContactFields cf = new ContactFields("Contact::Email", emailname, date);//ContactFields也是我自定义的一个对象，你可以根据需要定义自己的bean类
//                            contactitem.contact_fields.add(cf);
//
//                        } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)) {
//                            String note = contactInfoCursor.getString(
//                                    contactInfoCursor.getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Note.NOTE));
////       LogUtils.E("====note==="+note);
//                            contactitem.setNote(note);
//                        }
//                    }
//                    contacts.add(contactitem);
////     System.out.println("*********");
//                    contactInfoCursor.close();
//                }
//                cursor.close();
//
//                return null;
//            }
//
//
//        }.execute();


        ///////////////////////////////////////////////

        ContentResolver cr = getContentResolver();

        // 从  raw_contacts 中查询所有的人
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if (cursor.getCount() > 0) {

            while (cursor.moveToNext()) {

                String rawContactId = "";
                String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                Log.d("contactID", id);


                // 获取RawContacts表的游标
                Cursor rawContactCur = cr.query(ContactsContract.RawContacts.CONTENT_URI, null,
                        ContactsContract.RawContacts._ID + "=?", new String[]{id}, null);
                // 该查询结果一般只返回一条记录，所以我们直接让游标指向第一条记录
                if (rawContactCur.moveToFirst()) {
                    // 读取第一条记录的RawContacts._ID列的值
                    rawContactId = rawContactCur.getString(rawContactCur.getColumnIndex(ContactsContract.RawContacts._ID));
                    Log.v("rawContactID", rawContactId);
                }
                // 关闭游标
                rawContactCur.close();

                // 读取号码
                if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                    Cursor phoneCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID + "=?",
                            new String[]{rawContactId},
                            null);
                    // 上面的ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                    // 可以用下面的phoneUri代替
                    // Uri
                    // phoneUri=Uri.parse("content://com.android.contacts/data/phones");

                    // 一个联系人可能有多个号码，需要遍历
                    while (phoneCur.moveToNext()) {
                        // 获取号码
                        String number = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.v("number", number);
                        // 获取号码类型
                        String type = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                        Log.v("type", type);

                    }
                    phoneCur.close();
                }
            }
            cursor.close();
        }

//        mAsyncQureyHandler = new MyAsyncQureyHandler(getContentResolver());
//
//        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人Uri；
//        // 查询的字段
//        String[] projection = {ContactsContract.CommonDataKinds.Phone._ID,//
//                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,//
//                ContactsContract.CommonDataKinds.Phone.DATA1,//
//                "sort_key", //
//                ContactsContract.CommonDataKinds.Phone.DATA2,//
//                ContactsContract.CommonDataKinds.Phone.PHOTO_ID, //
//                ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY,
//
//                // TODO: 2018/8/17
//                ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME,
//                ContactsContract.CommonDataKinds.SipAddress.DISPLAY_NAME,
//                ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
//                ContactsContract.CommonDataKinds.Organization.DISPLAY_NAME,
//
//                ContactsContract.PhoneLookup.DISPLAY_NAME
//
//                //    ContactsContract.CommonDataKinds.
//
//
//        };
//        // 按照sort_key升序查詢
//        mAsyncQureyHandler.startQuery(0, null, uri, projection, null,
//                null, "sort_key COLLATE LOCALIZED asc");
    }


    private class MyAsyncQureyHandler extends AsyncQueryHandler {

        public MyAsyncQureyHandler(ContentResolver cr) {
            super(cr);
        }


        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            ArrayList<Folk> list = new ArrayList();
            Folk folk;
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst(); // 游标移动到第一项

                for (int i = 0; i < cursor.getCount(); i++) {
                    folk = new Folk();
                    cursor.moveToPosition(i);
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    String sortKey = cursor.getString(3);
                    int contactId = cursor.getInt(4);
                    Long photoId = cursor.getLong(5);
                    String lookUpKey = cursor.getString(6);

                    String GroupMembershipDISPLAY_NAME = cursor.getString(7);
                    String sip = cursor.getString(8);

                    String email = cursor.getString(9);
                    String org = cursor.getString(10);
                    String org1 = cursor.getString(11);


                    folk.setName(name);
                    folk.setPhones(number);
                    list.add(folk);

                }
            }
            if (list.size() > 0) {
                MyListAdapter arrayAdapter = showContactFromMobile(list);
                mContactFromMobileListView.setAdapter(arrayAdapter);
            }
        }

    }

    private MyListAdapter showContactFromMobile(ArrayList<Folk> list) {
        MyListAdapter adapter = new MyListAdapter(list);
        return adapter;
    }

    class MyListAdapter extends BaseAdapter {

        ArrayList<Folk> listFolk;

        public MyListAdapter(ArrayList<Folk> list) {
            listFolk = list;
        }

        @Override
        public int getCount() {
            return listFolk.size();
        }

        @Override
        public Folk getItem(int position) {
            return listFolk.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.each_body_detail, parent, false);
                holder = new ViewHolder();
                holder.personName = convertView.findViewById(R.id.item_personName);
                holder.personMobilePhone = convertView.findViewById(R.id.item_personMobilePhone);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.personName.setText(listFolk.get(position).getName());
            holder.personMobilePhone.setText(listFolk.get(position).getPhones());

            return convertView;
        }

        class ViewHolder {
            TextView personName;
            TextView personMobilePhone;
        }

    }


}
